/*
 * Copyright 2007 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.dev.jas.as.impl;

import com.google.gwt.dev.js.ast.JsBinaryOperation;
import com.google.gwt.dev.js.ast.JsBinaryOperator;
import com.google.gwt.dev.js.ast.JsContext;
import com.google.gwt.dev.js.ast.JsExpression;
import com.google.gwt.dev.js.ast.JsInvocation;
import com.google.gwt.dev.js.ast.JsModVisitor;
import com.google.gwt.dev.js.ast.JsNameRef;
import com.google.gwt.dev.js.ast.JsProgram;

/**
 * Eliminates uses of the "in" operator. For example, we convert this:
 * <blockquote>
 * <pre>
 *      foo in obj
 * </pre>
 * </blockquote>
 * into this:
 * <blockquote>
 * <pre>
 *      obj.hasOwnProperty(foo)
 * </pre>
 * </blockquote>
 *
 * <p>
 * This is necessary to make the program compatible with ActionScript 2.0.
 */
public final class JsInRemover {

  private static class Visitor extends JsModVisitor {

    @Override
    public void endVisit(JsBinaryOperation binop, JsContext ctx) {
      if (binop.getOperator() != JsBinaryOperator.INOP)
        return;
      JsInvocation invoke = new JsInvocation(binop.getSourceInfo());
      JsNameRef nameRef = new JsNameRef(binop.getSourceInfo(), "hasOwnProperty");
      nameRef.setQualifier(binop.getArg2());
      invoke.setQualifier(nameRef);
      invoke.getArguments().add(binop.getArg1());
      ctx.replaceMe(invoke);
    }
  }

  public static void exec(JsProgram program) {
    new Visitor().accept(program);
  }

  private JsInRemover() {
  }
}
